package msg;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.EJBException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Hashtable;


public class MessageBean implements MessageDrivenBean, MessageListener {
    private MessageDrivenContext messageContext = null;

    public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
    public final static String INIT_CTX = "t3://localhost:7001";
    public final static String JMS_FACTORY="QCF";
    private static final Logger logger = LoggerFactory.getLogger(MessageBean.class);

    public void setMessageDrivenContext(MessageDrivenContext messageContext) throws EJBException {
        this.messageContext = messageContext;
    }
    public void ejbCreate() {
    }
    public void ejbRemove() {
        messageContext = null;
    }
    public MessageBean() {
    }

    public InitialContext getInitialContext(String url)
    {
        // Using of interface Map<String, String> is not supported by InitialContext,
        // hence Hashtable implementation is used
        Hashtable<String, String> env = new Hashtable<String, String>();
        // Name of provider
        env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
        // Where provider is to be found
        env.put(Context.PROVIDER_URL, url);
        try {
            return new InitialContext(env);
        } catch (NamingException ex) {
            throw new RuntimeException(ex);
        }
    }

    public void onMessage(Message message) {
        System.out.println("Message Driven Bean got message " + message);
        logger.info("Inside onMessage!");

        Queue queue;
        InitialContext context = null;
        QueueConnectionFactory factory = null;
        QueueConnection connect = null;
        QueueSession session = null;
        QueueSender sender = null;
        try {
            queue = (Queue) message.getJMSReplyTo();

            context = getInitialContext(INIT_CTX);
            logger.info("Initial context was got!");

            factory = (QueueConnectionFactory)
                    context.lookup(JMS_FACTORY);
            logger.info("Connection Factory was found!");
            connect = factory.createQueueConnection();

            session = connect.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

            logger.info("Next I'll try to create sender for temp queue!");
            sender = session.createSender(queue);
            logger.info("Sender was created for temp queue!");

            TextMessage reply = session.createTextMessage();
            TextMessage textMsg = (TextMessage) message;
            reply.setText(textMsg.getText() + "*reply*");

            //msg.setText(msg.getText() + "*reply*");

            connect.start();
            logger.info("Connection started. Trying to send message...");
            sender.send(reply);
            logger.info("Message was sent back to the temp queue!");

        } catch (JMSException ex) {
            throw new RuntimeException(ex);
        } catch (NamingException e) {
            //logger.error("NamingException", e);
            throw new RuntimeException(e);
        } finally {
            if(connect != null) {
                try {
                    connect.close();
                } catch (JMSException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}